//
//  MyStockRadarEditControll.m
//  Stock
//
//  Created by blacksun on 11-7-8.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockRadarEditControll.h"
#import "LocalStockListController.h"


@implementation StockRadarEditControll
@synthesize tableView;
@synthesize pickerView;
@synthesize radar;
@synthesize values;
@synthesize myStockService;
@synthesize localStocks;
@synthesize localRadars;
@synthesize searchButton;
@synthesize textField;


- (void)dealloc{
    [tableView release];
    [pickerView release];
    [values release];
    [myStockService cancleAllRequest];
    [myStockService release];
    self.searchButton = nil;
    self.textField = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
#pragma mark -Service Delegate
-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    lastStatus = radar.status;
    //[[StockAppHelper shareInstance] showAlertViewWithMessage:@"保存成功" andDelegate:self];
    radar.id = [aResult objectForKey:@"id"];
    [radar save];
    [localRadars addObject:radar];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    radar.status = lastStatus;
    [[StockAppHelper shareInstance] showAlertViewWithMessage:@"保存失败"];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    NSLog(@"cancle");
    [self.navigationController popViewControllerAnimated:YES];
}
/*- (void)alertViewCancel:(UIAlertView *)alertView{
    NSLog(@"cancle2");
}*/
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"cancle3");
}
-(void)saveStockRadar{
    if ([radar.stockId isEqualToString:@""]) {
        [[StockAppHelper shareInstance] showAlertViewWithMessage:@"请设置对应的股票"];
        return;
    }
    if (![self.textField.text floatValue]) {
        [[StockAppHelper shareInstance] showAlertViewWithMessage:@"请输入正确的小数"];
        return;
    }
    radar.status = 2;
    radar.targetValue = [NSString stringWithFormat:@"%0.2f",[self.textField.text floatValue]];
    radar.type = [radar.targetValue floatValue]>[radar.currentValue floatValue]?kStockMonitorTypeUp:kStockMonitorTypeDown;
    [myStockService uploadStockRadar:radar];
}
-(void)switchViewValueDidChanged:(id)sender{
    UISwitch *switchView = (UISwitch *)sender;
    radar.repeat = switchView.on;
}

-(void)wantToResetStock{
    if (self.localStocks.count==0) {
        [[StockAppHelper shareInstance] showAlertViewWithMessage:@"请先将关注的股票添加到自选股，再设置预警阀值。"];
        return;
    }
    LocalStockListController *localController = [[LocalStockListController alloc] initWithNibName:@"LocalStockListController" bundle:nil];
    localController.localStocks = self.localStocks;
    localController.radar = self.radar;
    [self.navigationController pushViewController:localController animated:YES];
    [localController release];
}


-(void)resetStock{
    [self.values removeAllObjects];
    
    float price = 0.0;
    if (![radar.stockId isEqualToString:@""]) {
        NSArray *temp = [localStocks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.uuid=%@",radar.stockId]];
        MyStock *stock = temp.count>0?[temp objectAtIndex:0]:nil;
        radar.currentValue = [stock.closingPrice stringValue];
        price = [stock.closingPrice floatValue];
    }
    
    for (int i=100; i>0; i--) {
        [values addObject:[NSString stringWithFormat:@"%.2f",price*(1-0.01*i)]];
    }
    for (int i=0; i<101; i++) {
        [values addObject:[NSString stringWithFormat:@"%.2f",price*(1+0.01*i)]];
    }
    
    [self.tableView reloadData];
    [self.pickerView reloadAllComponents];

    [self.pickerView selectRow:100 inComponent:0 animated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"阀值预警";
    if (!self.radar) {
        self.radar = [StockRadar findByStockId:@"" andType:kStockMonitorTypeUp];
    }
    lastStatus = radar.status;
    self.myStockService = [[[MyStockService alloc] initWithDelegate:self] autorelease];
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveStockRadar)];
    
    self.navigationItem.rightBarButtonItem = rightButton;
    [rightButton release];
    
    self.values = [NSMutableArray array];
    
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0.0, 427.5, 105.0, 52.5);
    //doneButton.adjustsImageWhenHighlighted = NO;
    doneButton.showsTouchWhenHighlighted = YES;
    [doneButton setBackgroundImage:[UIImage imageNamed:@"query.png"] forState:UIControlStateNormal];
    [doneButton setTitle:@"." forState:UIControlStateNormal];
    [doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [doneButton addTarget:self action:@selector(clickedButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchButton = doneButton;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardWillHideNotification object:nil];
    
   
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self resetStock];
}
-(void)clickedButton:(id)sender{
    self.textField.text = [NSString stringWithFormat:@"%@.",self.textField.text];
}
-(void)keyboardDidHidden{
    NSLog(@"keyboardDidHidden");
    [self.searchButton removeFromSuperview];
}   


- (void)keyboardWillShow:(NSNotification *)note {
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    [tempWindow addSubview:searchButton];
    UILabel *titleLabel = searchButton.titleLabel;
    titleLabel.font = [UIFont boldSystemFontOfSize:20.0];
    titleLabel.shadowOffset = CGSizeMake(-0.5, -1.0);
    titleLabel.shadowColor = [UIColor grayColor];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [tableView release];
    [pickerView release];
    [values release];
    [myStockService cancleAllRequest];
    [myStockService release];
 
}

#pragma mark - tableView 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"stockRadarCell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:17.0];
        
        cell.detailTextLabel.textColor = [UIColor whiteColor];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    NSInteger row = indexPath.row;
    NSString *imageName = @"cellbg1.png";
    if (row%2==1) {
        imageName = @"cellbg2.png";
    }
    cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]] autorelease];
    
    /*UILabel *rightLabel = (UILabel *)[cell viewWithTag:1000];
    UISwitch *switchView = (UISwitch *)[cell viewWithTag:101];
    rightLabel.hidden = YES;
    switchView.hidden = YES;
    */
    if (row==0) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [button addTarget:self action:@selector(wantToResetStock) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = button;
        cell.textLabel.text = @"股票名称";
        if (![radar.stockId isEqualToString:@""]) {
            NSArray *array = [localStocks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.uuid=%@",radar.stockId]];
            MyStock *stock = array.count>0?[array objectAtIndex:0]:nil;
            cell.detailTextLabel.text = stock.name;
        }else{
            cell.detailTextLabel.text = @"请在自选股中选择";
        }
    }else if (row==1) {
        cell.textLabel.text = @"当前价";
        cell.detailTextLabel.text = radar.currentValue;
    }else if (row==2) {
        cell.textLabel.text = @"预警阀值";
        UITextField *temp = [[UITextField alloc] initWithFrame:CGRectMake(190.0, 6.0, 120.0, 31.0)];
        temp.text = radar.targetValue;
        temp.keyboardType = UIKeyboardTypeNumberPad;
        temp.borderStyle = UITextBorderStyleRoundedRect;
        temp.textAlignment = UITextAlignmentRight;
        [cell.contentView addSubview:temp];
        self.textField = temp;
        [temp becomeFirstResponder];
        [temp release];
        
    }/*else if (row==2) {
        cell.textLabel.text = @"预警差幅";
        rightLabel.hidden = NO;
        rightLabel.text = radar.targetPercent;
    }else if (row==2) {
        cell.textLabel.text = @"重复提醒";
        switchView.hidden = NO;
        switchView.on = radar.repeat;
    }*/ 
    return cell;
}


#pragma mark -PickerView 
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return values.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [values objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    radar.targetValue = [values objectAtIndex:row];
    radar.targetPercent = [NSString stringWithFormat:@"%d%%",row*1];
    [self.tableView reloadData];
}
@end
